
const redirectUriBase= 'https://tongwang.cc/tongwang/#' // 公众号回调地址域名

let account=''
/**
 * 获取微信公众号code并重定向
 */
export const getWeiXinCodeH5 = (_options) => {
    account=_options.account
    const config = {
        appId: 'wx0ff9275e332c1916', // 公众号appId
        redirectUri: encodeURIComponent(redirectUriBase+`/pages/load/index?account=${_options.account}`) // 授权回调地址
    }

    // 处理授权回调
    const code = getUrlParam('code');
    console.log('获取到了微信公众号code', code)
    if (code) {
        console.log('code',code)
        loginHandler(code)
    } else {
        const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${config.appId}&redirect_uri=${config.redirectUri}&response_type=code&scope=snsapi_base#wechat_redirect`;

        // 跳转到授权页面
        window.location.href = authUrl;
    }
}

const userInfo=qly.storage.storageRef('userInfo')
const token=qly.storage.storageRef('token')
const uid=qly.storage.storageRef('uid')
const login=qly.storage.storageRef('login')

const loginHandler= async (code)=>{
    const res= await qly.api.auth.wxlogin({code,pid:account})
    if(res.code===1){
        userInfo.value=res.data
        uid.value=res.data.id
        token.value=res.data.token
        login.value=true

        setTimeout(() => {
            qly.page.open('/pages/tabBar/home/index')
        }, 1000)
    }else {
        login.value=false
        qly.dialog.toast({title:res.info})
    }

}

/**
 * 获取url中的参数值
 * @param name
 * @returns {string|null}
 */
export const getUrlParam = (name) => {
    const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
    const r = window.location.search.substr(1).match(reg);
    return r ? decodeURIComponent(r[2]) : null;
}
